// 发布订阅事件中心
module.exports = class PubSub {
    constructor() {
        // 维护事件及订阅行为
        this.events = {}
    }
    // 注册订阅事件
    subscribe(type, cb) {
        if (!this.events[type]) {
            this.events[type] = []
        }
        this.events[type].push(cb)
    }
    // 发布事件
    publish(type, ...args) {
        if (this.events[type]) {
            this.events[type].forEach(cb => {
                cb(...args)
            })
        }
    }
    // 移除订阅
    unsubscribe(type, cb) {
        if (this.events[type]) {
            const targetIndex = this.events[type].findIndex(item => item === cb)
            if (targetIndex !== -1) {
                this.events[type].splice(targetIndex, 1)
            }
            if (this.events[type].length === 0) {
                delete this.events[type]
            }
        }
    }
    // 移除某个事件的所有订阅行为
    unsubscribeAll(type) {
        if (this.events[type]) {
            delete this.events[type]
        }
    }
}